import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xiaofanshu_flutter/apis/app.dart';
import 'package:xiaofanshu_flutter/model/response.dart';
import 'package:xiaofanshu_flutter/static/custom_code.dart';
import 'package:xiaofanshu_flutter/static/custom_color.dart';
import 'package:xiaofanshu_flutter/controller/mine_controller.dart';
import 'package:xiaofanshu_flutter/utils/snackbar_util.dart';

class AchievementDetailPage extends StatefulWidget {
  const AchievementDetailPage({super.key});

  @override
  State<AchievementDetailPage> createState() => _AchievementDetailPageState();
}

class _AchievementDetailPageState extends State<AchievementDetailPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final MineController mineController = Get.find();

  // Level Data
  var currentLevel = 1.obs;
  var levelTitle = '新手'.obs;
  var currentExp = 0.obs;
  var nextLevelExp = 100.obs;
  var progressPercent = 0.0.obs;

  // Achievements Data
  var achievements = <Map<String, dynamic>>[].obs;

  // Exp Log Data
  var expLogs = <Map<String, dynamic>>[].obs;
  var expLogPageNum = 1;
  var expLogPageSize = 10;
  var expLogHasMore = true.obs;
  var expLogIsLoading = false.obs;
  ScrollController _expLogScrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _initData();
    _expLogScrollController.addListener(_onExpLogScroll);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _expLogScrollController.dispose();
    super.dispose();
  }

  Future<void> _initData() async {
    int userId = mineController.userInfo.value.id;
    if (userId == 0) {
      SnackbarUtil.showError('用户ID获取失败，请重新登录');
      Get.back();
      return;
    }
    await Future.wait([
      _loadUserLevel(),
      _loadUserAchievements(),
      _loadUserExpLog(),
    ]);
  }

  Future<void> _loadUserLevel() async {
    int userId = mineController.userInfo.value.id;
    try {
      HttpResponse response = await AchievementApi.getUserLevel(userId);
      if (response.code == StatusCode.getSuccess && response.data != null) {
        currentLevel.value = response.data['currentLevel'] ?? 1;
        levelTitle.value = response.data['levelTitle'] ?? '新手';
        currentExp.value = response.data['currentExp'] ?? 0;
        nextLevelExp.value = response.data['nextLevelExp'] ?? 100;
        progressPercent.value = (currentExp.value / nextLevelExp.value).clamp(0.0, 1.0);
      } else {
        SnackbarUtil.showError('获取用户等级失败: ${response.msg}');
      }
    } catch (e) {
      Get.log('获取用户等级出错: $e');
      SnackbarUtil.showError('获取用户等级出错');
    }
  }

  Future<void> _loadUserAchievements() async {
    int userId = mineController.userInfo.value.id;
    try {
      HttpResponse response = await AchievementApi.getUserAchievements(userId);
      if (response.code == StatusCode.getSuccess && response.data != null) {
        achievements.value = List<Map<String, dynamic>>.from(response.data);
      } else {
        SnackbarUtil.showError('获取成就列表失败: ${response.msg}');
      }
    } catch (e) {
      Get.log('获取成就列表出错: $e');
      SnackbarUtil.showError('获取成就列表出错');
    }
  }

  Future<void> _loadUserExpLog({bool isLoadMore = false}) async {
    int userId = mineController.userInfo.value.id;
    if (expLogIsLoading.value || (!expLogHasMore.value && isLoadMore)) return;

    expLogIsLoading.value = true;
    try {
      HttpResponse response = await AchievementApi.getUserExpLog(userId, expLogPageNum, expLogPageSize);
      if (response.code == StatusCode.getSuccess && response.data != null) {
        List<dynamic> newLogs = response.data['records'] ?? [];
        if (!isLoadMore) {
          expLogs.clear();
        }
        expLogs.addAll(List<Map<String, dynamic>>.from(newLogs));
        expLogPageNum++;
        expLogHasMore.value = (expLogs.length < (int.tryParse(response.data['total']) ?? 0));
      } else {
        SnackbarUtil.showError('获取经验记录失败: ${response.msg}');
      }
    } catch (e) {
      Get.log('获取经验记录出错: $e');
      SnackbarUtil.showError('获取经验记录出错');
    } finally {
      expLogIsLoading.value = false;
    }
  }

  void _onExpLogScroll() {
    if (_expLogScrollController.position.pixels == _expLogScrollController.position.maxScrollExtent) {
      _loadUserExpLog(isLoadMore: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('等级与成就'),
        backgroundColor: CustomColor.primaryColor,
        foregroundColor: Colors.white,
      ),
      body: Column(
              children: [
                // 顶部等级信息卡片
                _buildLevelCard(),
                // Tab 栏
                TabBar(
                  controller: _tabController,
                  labelColor: CustomColor.primaryColor,
                  unselectedLabelColor: Colors.grey,
                  indicatorColor: CustomColor.primaryColor,
                  tabs: const [
                    Tab(text: '成就列表'),
                    Tab(text: '经验记录'),
                    Tab(text: '规则说明'),
                  ],
                ),
                // Tab 内容
                Expanded(
                  child: TabBarView(
                    controller: _tabController,
                    children: [
                      _buildAchievementList(),
                      _buildExpLogList(),
                      _buildRules(),
                    ],
                  ),
                ),
              ],
            ),
    );
  }

  Widget _buildLevelCard() {
    return Obx(() => Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            CustomColor.primaryColor,
            CustomColor.primaryColor.withOpacity(0.7),
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: CustomColor.primaryColor.withOpacity(0.3),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.3),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          'Lv.${currentLevel.value}',
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Text(
                        levelTitle.value,
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '${currentExp.value} / ${nextLevelExp.value} EXP',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.white.withOpacity(0.9),
                    ),
                  ),
                ],
              ),
              Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  shape: BoxShape.circle,
                ),
                child: Center(
                  child: Text(
                    '${(progressPercent.value * 100).toStringAsFixed(0)}%',
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: LinearProgressIndicator(
              value: progressPercent.value,
              minHeight: 10,
              backgroundColor: Colors.white.withOpacity(0.3),
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
            ),
          ),
          const SizedBox(height: 12),
          const Text(
            '继续努力，解锁更多等级和特权！',
            style: TextStyle(
              fontSize: 13,
              color: Colors.white,
            ),
          ),
        ],
      ),
    ));
  }

  Widget _buildAchievementList() {
    return Obx(() {
    if (achievements.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.emoji_events_outlined, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text(
              '暂无成就',
              style: TextStyle(fontSize: 16, color: Colors.grey),
            ),
          ],
        ),
      );
    }

    int completedCount = achievements.where((a) => a['isCompleted'] == true).length;

    return Column(
      children: [
        // 成就统计
        Container(
          padding: const EdgeInsets.all(16),
          color: const Color(0xfff8f8f8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatItem('总成就', achievements.length.toString()),
              Container(
                width: 1,
                height: 30,
                color: Colors.grey.withOpacity(0.3),
              ),
              _buildStatItem('已完成', completedCount.toString()),
              Container(
                width: 1,
                height: 30,
                color: Colors.grey.withOpacity(0.3),
              ),
              _buildStatItem(
                '完成率',
                '${((completedCount / achievements.length) * 100).toStringAsFixed(0)}%',
              ),
            ],
          ),
        ),
        // 成就卡片列表
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: achievements.length,
            itemBuilder: (context, index) {
              final achievement = achievements[index];
              return _buildAchievementCard(achievement);
            },
          ),
        ),
      ],
    );
    });
  }

  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: CustomColor.primaryColor,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Color(0xff999999),
          ),
        ),
      ],
    );
  }

  Widget _buildAchievementCard(Map<String, dynamic> achievement) {
    bool isCompleted = achievement['isCompleted'] ?? false;
    String name = achievement['name'] ?? '';
    String description = achievement['description'] ?? '';
    int expReward = achievement['expReward'] ?? 0;
    int currentProgress = achievement['currentProgress'] ?? 0;
    int targetProgress = achievement['targetProgress'] ?? 1;

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: isCompleted ? const Color(0xfffff5e6) : Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: isCompleted
              ? const Color(0xffff9800)
              : Colors.grey.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          // 成就图标
          Container(
            width: 56,
            height: 56,
            decoration: BoxDecoration(
              color: isCompleted
                  ? const Color(0xffff9800)
                  : Colors.grey.withOpacity(0.2),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(
              isCompleted ? Icons.emoji_events : Icons.emoji_events_outlined,
              color: isCompleted ? Colors.white : Colors.grey,
              size: 32,
            ),
          ),
          const SizedBox(width: 16),
          // 成就信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        name,
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: isCompleted
                              ? Colors.black87
                              : const Color(0xff999999),
                        ),
                      ),
                    ),
                    if (isCompleted)
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 2,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xffff9800),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: const Text(
                          '已完成',
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.white,
                          ),
                        ),
                      ),
                  ],
                ),
                const SizedBox(height: 4),
                Text(
                  description,
                  style: TextStyle(
                    fontSize: 13,
                    color: isCompleted
                        ? const Color(0xff666666)
                        : const Color(0xffaaaaaa),
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Icon(
                      Icons.stars,
                      size: 14,
                      color: isCompleted ? const Color(0xffff9800) : Colors.grey,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      '+$expReward EXP',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: isCompleted
                            ? const Color(0xffff9800)
                            : Colors.grey,
                      ),
                    ),
                    const Spacer(),
                    Text(
                      '$currentProgress / $targetProgress',
                      style: TextStyle(
                        fontSize: 12,
                        color: isCompleted
                            ? const Color(0xff666666)
                            : const Color(0xffaaaaaa),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildExpLogList() {
    return Obx(() {
    if (expLogs.isEmpty && !expLogIsLoading.value) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.history, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text(
              '暂无经验记录',
              style: TextStyle(fontSize: 16, color: Colors.grey),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      controller: _expLogScrollController,
      padding: const EdgeInsets.all(16),
      itemCount: expLogs.length + (expLogHasMore.value ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == expLogs.length) {
          return const Center(child: CircularProgressIndicator.adaptive());
        }
        final log = expLogs[index];
        return _buildExpLogItem(log);
      },
    );
    });
  }

  Widget _buildExpLogItem(Map<String, dynamic> log) {
    String description = log['description'] ?? '';
    int expAmount = log['expValue'] ?? 0;
    String createTime = log['createTime'] ?? '';

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: Colors.grey.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: CustomColor.primaryColor.withOpacity(0.1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Icon(
              Icons.add_circle_outline,
              color: CustomColor.primaryColor,
              size: 24,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  description,
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  createTime,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xff999999),
                  ),
                ),
              ],
            ),
          ),
          Text(
            '+$expAmount EXP',
            style: const TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              color: Colors.green,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRules() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildRuleSection(
            title: '💎 经验值获取规则',
            items: [
              {'action': '发布笔记', 'exp': '+10 EXP'},
              {'action': '创建路线', 'exp': '+20 EXP'},
              {'action': '笔记被点赞', 'exp': '+5 EXP'},
              {'action': '路线被点赞', 'exp': '+5 EXP'},
              {'action': '笔记被收藏', 'exp': '+8 EXP'},
              {'action': '首次访问城市', 'exp': '+15 EXP'},
            ],
          ),
          const SizedBox(height: 24),
          _buildRuleSection(
            title: '🏆 触发成就说明',
            items: [
              {'action': '发布笔记', 'exp': '故事猎人、城市探索者、夜猫子'},
              {'action': '创建路线', 'exp': '路线规划师'},
              {'action': '笔记被点赞', 'exp': '社交达人'},
              {'action': '路线被点赞', 'exp': '社交达人'},
              {'action': '笔记被收藏', 'exp': '社交达人'},
              {'action': '首次访问城市', 'exp': '城市探索者'},
            ],
          ),
          const SizedBox(height: 24),
          _buildInfoCard(),
        ],
      ),
    );
  }

  Widget _buildRuleSection({
    required String title,
    required List<Map<String, String>> items,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 12),
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: Colors.grey.withOpacity(0.2),
              width: 1,
            ),
          ),
          child: Column(
            children: items
                .map((item) => _buildRuleItem(
                      item['action']!,
                      item['exp']!,
                      items.last != item,
                    ))
                .toList(),
          ),
        ),
      ],
    );
  }

  Widget _buildRuleItem(String action, String exp, bool showDivider) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                action,
                style: const TextStyle(
                  fontSize: 15,
                  color: Colors.black87,
                ),
              ),
              Text(
                exp,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: exp.contains('+')
                      ? const Color(0xff4caf50)
                      : CustomColor.primaryColor,
                ),
              ),
            ],
          ),
        ),
        if (showDivider)
          Divider(
            height: 1,
            indent: 16,
            endIndent: 16,
            color: Colors.grey.withOpacity(0.2),
          ),
      ],
    );
  }

  Widget _buildInfoCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            const Color(0xffe3f2fd),
            const Color(0xffe1f5fe),
          ],
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.info_outline,
                color: CustomColor.primaryColor,
                size: 20,
              ),
              const SizedBox(width: 8),
              const Text(
                '温馨提示',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          const Text(
            '• 等级越高，解锁更多特权功能\n'
            '• 完成成就可获得额外经验奖励\n'
            '• 每日首次操作获得双倍经验\n'
            '• 分享故事到社交平台额外 +3 EXP',
            style: TextStyle(
              fontSize: 13,
              color: Color(0xff666666),
              height: 1.6,
            ),
          ),
        ],
      ),
    );
  }
}
